<!-- 目前按图片格式处理，扫描件上传也只上传图片，查看扫描件的时候以图片处理。 -->

<template>
  <div>
    <el-upload
      action="/ccdc/sys/common/upload"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :multiple="multiple"
      :on-exceed="handleExceed"
      :on-success="handleChange"
      accept="image/*"
      :limit="limit"
      :headers="headers"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import { PopupCommon } from "@/libs/popupCommon";
export default {
  props: {
    /** 文件限制个数 1-100 */
    limit: {
      type: Number,
      require,
    },
    /** 是否支持多选 */
    multiple: {
      type: Boolean,
      require,
    },
  },
  data() {
    return {
      headers: {},
      /** 选择的文件集合 */
      fileLists: "",
      dialogImageUrl: "",
      dialogVisible: false,
    };
  },
  methods: {
    /** 文件限制 */
    handleExceed(files, fileList) {
      PopupCommon.notify(
        "info",
        `超过文件个数限制（${this.limit}），此次上传无效。`
      );
      console.log(
        `本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    /** 文件删除 */
    handleRemove(file, fileList) {
      console.log(fileList, this.fileLists);
      // 这里只会有图片上传，不会有回显。
      const fileName = file.response.message;
      let value = this.fileLists.split(",");
      const fIndex = value.findIndex((t) => t == fileName);
      value = value.splice(fIndex + 1, 1);
      this.fileLists = value.join(",");
      this.$emit("uploadFileHandle", this.fileLists);
    },
    /** 文件选择后的操作 */
    handleChange(file, fileList) {
      let value = this.fileLists;
      if (
        value == "" ||
        value == undefined ||
        typeof value == "undefined" ||
        value == null
      ) {
        value = file.message;
      } else {
        value = value + "," + file.message;
      }
      this.fileLists = value;
      this.$emit("uploadFileHandle", this.fileLists);
      console.log(this.fileLists);
      console.log(fileList, this.fileLists);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    initData() {
      let projectTestperiod =
        window.sessionStorage.getItem("projectTestperiod");
      if (projectTestperiod) {
        projectTestperiod = JSON.parse(projectTestperiod);
        // 上传时需要
        this.headers = {
          "X-Access-Token": localStorage.getItem("token"),
          pmId: projectTestperiod.projectId,
          expId: projectTestperiod.testId,
          periodNo: projectTestperiod.periodId,
        };
      } else {
        // this.$router.replace({
        //     name: "userLogin",
        // });
        this.$router.replace({
          name: "/",
        });
      }
    },
  },
  mounted() {
    this.initData();
  },
};
</script>

<style></style>